<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="zbmc">
        <el-input v-model="queryParams.zbmc" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备编号" prop="sbbh">
        <el-input v-model="queryParams.sbbh" placeholder="请输入设备编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="上报人" prop="sbr">
        <el-input v-model="queryParams.sbr" placeholder="请输入上报人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
<!--      <el-form-item label="上报单位" prop="sbdw">-->
<!--        <el-input v-model="queryParams.sbdw" placeholder="请输入上报单位" clearable @keyup.enter.native="handleQuery" />-->
<!--      </el-form-item>-->
      <el-form-item label="处理人" prop="clr">
        <el-select v-model="queryParams.clr" placeholder="请选择处理人" clearable filterable style="width: 100%">
          <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="maintenanceList">
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="zbmc" />
      <el-table-column label="设备编号" align="center" prop="sbbh" />
      <el-table-column label="上报人" align="center" prop="sbr" />
<!--      <el-table-column label="上报单位" align="center" prop="sbdw" />-->
      <el-table-column label="上报时间" align="center" prop="sbsj" />
      <el-table-column label="处理时间" align="center" prop="clsj" />
      <el-table-column label="处理人" align="center" prop="clrname" />
      <el-table-column label="处理描述" align="center" prop="clms" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div v-if="scope.row.type == 1">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate1(scope.row)">查看</el-button>
          </div>
          <div v-else>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:maintenance:edit']">已完成</el-button>
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate2(scope.row)">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:maintenance:remove']">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改告警处理对话框 -->
    <el-dialog title="已完成" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="处理时间" prop="clsj">
          <el-date-picker v-model="form.clsj" type="datetime" placeholder="选择时间" value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="处理人" prop="clr">
          <el-select v-model="form.clr" placeholder="请选择处理人" style="width: 100%">
            <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理描述" prop="clms">
          <el-input v-model="form.clms" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <input type="hidden" name="type" value="1">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改告警处理对话框 -->
    <el-dialog title="查看" :visible.sync="open1" width="800px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules" label-width="90px">
        <!-- 设备信息下拉选择 -->
        <el-form-item label="所属风场" prop="ssfcmc">
          <el-input v-model="form1.ssfcmc" placeholder="请输入所属风场" readonly disabled />
        </el-form-item>
        <el-form-item label="选择设备" prop="deviceInfo">
          <el-input v-model="form1.zbmc" placeholder="请输入设备" readonly disabled />
        </el-form-item>
        <!-- 其他表单字段保持不变 -->
        <el-form-item label="故障类型" prop="sbsx">
          <el-input v-model="form1.sbsx" placeholder="请输入故障类型" readonly disabled />
        </el-form-item>
        <el-form-item label="上报人" prop="sbr">
          <el-input v-model="form1.sbr" placeholder="请输入上报人" readonly disabled />
        </el-form-item>
<!--        <el-form-item label="上报单位" prop="sbdw">-->
<!--          <el-input v-model="form1.sbdw" placeholder="请输入上报单位" readonly disabled />-->
<!--        </el-form-item>-->
        <el-form-item label="上报时间" prop="sbsj">
          <el-date-picker v-model="form1.sbsj" type="date" readonly disabled placeholder="选择日期"
            value-format="yyyy-MM-dd " style="width: 100%;" />
        </el-form-item>
        <el-form-item label="故障描述" prop="gzms">
          <el-input v-model="form1.gzms" type="textarea" readonly disabled placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片和视频" prop="picVideo">
          <template v-if="hasMediaContent(form1.picVideo)">
            <imageV-upload1
              v-model="form1.picVideo"
              :image-limit="5"
              readonly
              disabled
              :video-limit="5"
              :file-size="2"
              :video-size="100"
            />
          </template>
          <div v-else class="empty-placeholder">
            空
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user"
import { listMaintenance, getMaintenance, delMaintenance, addMaintenance, updateMaintenance } from "@/api/system/maintenance"

export default {
  name: "Maintenance",
  data() {
    return {
      // 新增用户选项
      userOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 告警处理表格数据
      maintenanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zbmc: null,
        sbbh: null,
        sbr: null,
        sbdw: null,
        clr: null,
      },
      // 表单参数
      form: {},
      form1: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
    this.fetchTurbineList()
    this.getUserList() // 新增：获取用户列表
  },
  methods: {
    hasMediaContent(content) {
    if (!content) return false;
    if (Array.isArray(content)) return content.length > 0;
    if (typeof content === 'string') return content.trim() !== '';
    if (typeof content === 'object') return Object.keys(content).length > 0;
    return false;
  },
    async fetchTurbineList() {
    },
    // 新增：获取用户列表方法
    async getUserList() {
      try {
        const response = await listUser()
        if (response.code === 200) {
          this.userOptions = response.rows
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },
    handleDeviceChange(selected) {
      if (selected) {
        // 更新表单字段
        this.form.zbmc = selected.turbineCode  // 设备名称
        this.form.sbbh = selected.turbineModel // 设备编号
        this.form.sbid = selected.id          // 设备ID

        // 更新deviceInfo为选中对象（确保是引用相同的对象）
        const selectedItem = this.deviceOptions.find(item => item.id === selected.id)
        this.form.deviceInfo = selectedItem
      } else {
        // 清空选择
        this.clearDeviceSelection()
      }
    },
    /** 查询告警处理列表 */
    getList() {
      this.loading = true
      listMaintenance(this.queryParams).then(response => {
        this.maintenanceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮
    cancel1() {
      this.open1 = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        zbmc: null,
        sbbh: null,
        sbid: null,
        sbsx: null,
        sbr: null,
        sbdw: null,
        sbsj: null,
        picVideo: null,
        gzms: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        type: null,
        clsj: null,
        clr: null,
        clms: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMaintenance(id).then(response => {
        this.form = response.data
        // 查找对应的用户名称
        const selectedUser = this.userOptions.find(user => user.userId == this.form.clr)
        if (selectedUser) {
          this.form.clrname = selectedUser.nickName // 临时存储名称用于显示
        }
        this.open = true
        this.title = "修改告警处理"
      })
    },
    /** 修改按钮操作 */
    handleUpdate1(row) {
      const id = row.id || this.ids
      getMaintenance(id).then(response => {
        this.form1 = response.data
        this.open1 = true
        this.title = ""
      })
    },
    /** 修改按钮操作 */
    handleUpdate2(row) {
      const id = row.id || this.ids
      getMaintenance(id).then(response => {
        this.form1 = response.data
        this.open1 = true
        this.title = ""
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 查找选中的用户
          const selectedUser = this.userOptions.find(user => user.userId == this.form.clr)
          if (selectedUser) {
            this.form.clrname = selectedUser.nickName // 保存名称
          }

          this.form.type = 1
          updateMaintenance(this.form).then(response => {
            this.$modal.msgSuccess("成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除告警处理编号为"' + ids + '"的数据项？').then(function () {
        return delMaintenance(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/maintenance/export', {
        ...this.queryParams
      }, `maintenance_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style>
.df {
  display: flex;
}

.dfBetween {
  justify-content: space-between;
}

.w50 {
  width: 50%;
}

.w33 {
  width: 33%;
}
</style>
